package com.example.practice.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesDecryptor {
    
    public static String decrypt(String encryptedBase64, String secretKey) throws Exception {
        // Base64解码
        byte[] encryptedData = Base64.getDecoder().decode(encryptedBase64);
        
        // 提取IV (前16字节)
        byte[] iv = new byte[16];
        System.arraycopy(encryptedData, 0, iv, 0, 16);
        
        // 提取真实密文 (16字节之后)
        byte[] ciphertext = new byte[encryptedData.length - 16];
        System.arraycopy(encryptedData, 16, ciphertext, 0, ciphertext.length);
        
        // 初始化AES解密器
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
        
        // 解密并返回字符串
        byte[] decrypted = cipher.doFinal(ciphertext);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        // 与JavaScript一致的32字节密钥
        String secretKey = "1234567890abcdef1234567890abcdef";
        
        // JavaScript生成的加密结果 (替换为实际值)
        String encryptedFromJS = "cZq4qmRfdoOOH8tu4ToW871/uEn8EhLdFBiHETpw7+d2IJesYks3g5lbb60f1ce3"; // 替换为控制台输出的Base64字符串
        
        // 解密
        String decrypted = decrypt(encryptedFromJS, secretKey);
        System.out.println("解密结果: " + decrypted); // 输出: Hello, Java Decryption!
    }
}